package com.njust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.njust.domain.dto.ProductDTO;
import com.njust.domain.dto.ProductPageQueryDTO;
import com.njust.domain.po.Product;
import com.njust.domain.po.Project;
import com.njust.domain.po.Sample;
import com.njust.domain.po.User;
import com.njust.domain.vo.PageQueryVO;
import com.njust.exception.ProductAlreadyExists;
import com.njust.mapper.ProductMapper;
import com.njust.mapper.ProjectMapper;
import com.njust.mapper.SampleMapper;
import com.njust.service.ProductService;
import com.njust.service.ProjectService;
import com.njust.service.SampleService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author Imak
 * @Date 2024/11/7 13:05
 * @注释
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private SampleService sampleService;

    @Autowired
    private SampleMapper sampleMapper;

    private final Object lock = new Object();
    public int add(ProductDTO productDTO) {
        // 使用同步代码块，确保同一时间只有一个线程能执行插入同名产品的判断和插入操作
        synchronized (lock) {
            // 先查询是否已存在同名产品
            Product existingProduct = productMapper.findByProductName(productDTO.getProduct_name());

            if (existingProduct == null) {
                Product product = Product.builder()
                        .large_category(productDTO.getLarge_category())
                        .category(productDTO.getCategory())
                        .product_name(productDTO.getProduct_name())
                        .standard_number(productDTO.getStandard_number())
                        .description(productDTO.getDescription())
                        .build();
                return productMapper.insert(product);
            } else {
                return -1; // 返回 -1 表示插入失败，因为产品名称已存在
            }
        }
    }

    /**
     * 批量修改
     * @param productDTOList
     * @return
     */
    public int update(List<ProductDTO> productDTOList){
        // 创建一个用于存储要更新的Product实体对象的列表
        List<Product> productList = productDTOList.stream()
                .map(productDTO -> Product.builder()
                        .product_id(productDTO.getProduct_id())
                        .large_category(productDTO.getLarge_category())
                        .category(productDTO.getCategory())
                        .product_name(productDTO.getProduct_name())
                        .standard_number(productDTO.getStandard_number())
                        .description(productDTO.getDescription())
                        .build())
                .collect(Collectors.toList());

        // 遍历要更新的产品列表，逐个调用更新方法并累计更新成功的数量
        int updatedCount = 0;
        for (Product product : productList) {
            updatedCount += productMapper.updateById(product);
        }

        return updatedCount;
    }

    public PageQueryVO pageQuery(ProductPageQueryDTO productPageQueryDTO) {
        PageHelper.startPage(productPageQueryDTO.getPage(), productPageQueryDTO.getPageSize());
        Page<Product> page = productMapper.pageQuery(productPageQueryDTO.getProduct_name());
        long total = page.getTotal();
        List<Product> products = page.getResult();
        return new PageQueryVO(total, products);
    }

    @Transactional
    public int delete(Integer id){
        //先删下面的项目
        QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.eq("product_id",id);
        List<Project> projectList=projectMapper.selectList(wrapper);
        for(Project p:projectList){
            projectService.delete(p.getProject_id());
        }
        //删除产品对应的样品表-》样品需求表
        List<Sample> sampleList=sampleMapper.selectList(wrapper);
        for(Sample s:sampleList){
            sampleService.delete(s.getSample_id());
        }
        return productMapper.deleteById(id);
    }
}
